<template>
    <div class="sales-return-container">
        <!-- 搜索栏 -->
        <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
            <el-input v-model="searchParams.returnNo" style="width: 240px; padding-right: 15px;" placeholder="请输入退货单号" />
            <el-input v-model="searchParams.outboundNo" style="width: 240px;" placeholder="请输入出库单号" />
<!--            <el-date-picker v-model="searchParams.startDate" type="date" placeholder="起始日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="margin-right: 10px;margin-left: 10px; width: 150px;" />-->
<!--            <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="width: 150px;" />-->
            <el-icon @click="getSalesReturnList()" style="margin-left: 20px; height: 25px; width: 25px;">
                <Search />
            </el-icon>
            <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
                <Refresh />
            </el-icon>
            <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建销售退货单</el-button>
        </div>

        <!-- 销售退货单表格 -->
        <el-table :data="salesReturnList" style="width: 100%" stripe border="true">
            <el-table-column label="序号" width="80px" #default="scope" align="center">
                {{ scope.$index + 1 }}
            </el-table-column>
            <el-table-column prop="id" label="退货单ID" width="180" align="center" />
            <el-table-column prop="returnNo" label="退货单号" width="180" align="center" />
            <el-table-column prop="outboundNo" label="出库单号" width="180" align="center" />
            <el-table-column prop="warehouseName" label="仓库名称" width="180" align="center" />
            <el-table-column prop="returnDate" label="退货日期" width="180" align="center" />
            <el-table-column prop="status" label="退货状态" width="120" #default="scope" align="center">
                <span v-if="scope.row.status == 0" style="color: gray;">草稿</span>
                <span v-if="scope.row.status == 1" style="color: green;">已退货</span>
                <span v-if="scope.row.status == 2" style="color: red;">已取消</span>
            </el-table-column>
            <el-table-column label="操作" width="250px" fixed="right" align="center" #default="scope">
                <el-button type="primary" plain @click="viewSalesReturnDetails(scope.row.id)">详情</el-button>
                <el-button type="warning" plain @click="showEditDialog(scope.row)">修改</el-button>
                <el-button type="danger" plain @click="handleDeleteSalesReturn(scope.row.id)">删除</el-button>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
            <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                :page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 创建/编辑销售退货单对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑销售退货单' : '创建销售退货单'" width="900px"
            :before-close="handleDialogClose" :close-on-click-modal="false">
            <el-form :model="salesReturn" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="returnForm">
                <el-form-item label="退货单号" prop="returnNo" v-if="isEdit">
                    <el-input v-model="salesReturn.returnNo" disabled placeholder="系统自动生成" />
                </el-form-item>
                <el-form-item label="出库单号" prop="outboundId">
                    <el-select v-model="salesReturn.outboundId" placeholder="请选择出库单" clearable @change="handleOutboundChange">
                        <el-option v-for="outbound in salesOutbounds" :key="outbound.id" :label="outbound.outboundNo" :value="outbound.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="仓库名称" prop="warehouseId">
                    <el-input v-model="warehouseName" disabled placeholder="根据出库单自动显示" />
                </el-form-item>
                <el-form-item label="退货日期" prop="returnDate">
                    <el-date-picker v-model="salesReturn.returnDate" type="date" placeholder="请选择退货日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="退货状态" prop="status" v-if="isEdit">
                    <el-select v-model="salesReturn.status" placeholder="请选择退货状态">
                        <el-option label="已退货" :value="1" />
                        <el-option label="已取消" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="salesReturn.remark" type="textarea" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>
            <!-- 新增：退货商品明细表格 -->
            <div style="margin: 10px 0 0 0;">
                <h4>退货商品明细</h4>
                <el-table :data="salesReturn.items || []" style="width: 100%; margin-bottom: 10px;">
                    <el-table-column label="序号" width="60" #default="scope" align="center">
                        {{ scope.$index + 1 }}
                    </el-table-column>
                    <el-table-column label="产品" width="200" #default="scope" align="center">
                        <span>{{ scope.row.productName || '未知产品' }}</span>
                    </el-table-column>
                    <el-table-column label="产品编码" width="150" #default="scope" align="center">
                        <span>{{ scope.row.productCode || '-' }}</span>
                    </el-table-column>
                    <el-table-column label="数量" width="170" #default="scope" align="center">
                        <span>{{ scope.row.quantity || 0 }}</span>
                    </el-table-column>
                    <el-table-column label="单价" width="170" #default="scope" align="center">
                        <span>{{ scope.row.unitPrice || 0 }}</span>
                    </el-table-column>
                    <el-table-column label="金额" width="120" #default="scope" align="center">
                        <span>{{ scope.row.amount || 0 }}</span>
                    </el-table-column>
                </el-table>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose" size="default">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 销售退货单详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="销售退货单详情" width="900px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
            <div v-if="currentSalesReturn" class="sales-detail">
                <div class="detail-header">
                    <p><span class="label">退货单号：</span>{{ currentSalesReturn.returnNo }}</p>
                    <p><span class="label">出库单号：</span>{{ currentSalesReturn.outboundNo }}</p>
                    <p><span class="label">仓库名称：</span>{{ currentSalesReturn.warehouseName }}</p>
                    <p><span class="label">退货日期：</span>{{ currentSalesReturn.returnDate }}</p>
                    <p><span class="label">退货状态：</span>
                        <span v-if="currentSalesReturn.status == 0" style="color: gray;">草稿</span>
                        <span v-if="currentSalesReturn.status == 1" style="color: green;">已退货</span>
                        <span v-if="currentSalesReturn.status == 2" style="color: red;">已取消</span>
                    </p>
                    <p><span class="label">备注：</span>{{ currentSalesReturn.remark }}</p>
                </div>

                <div class="detail-items">
                    <h3>销售退货单明细</h3>
                    <el-table :data="currentSalesReturn.items" style="width: 100%" stripe>
                        <el-table-column label="序号" width="80px" #default="scope" align="center">
                            {{ scope.$index + 1 }}
                        </el-table-column>
                        <el-table-column prop="productName" label="产品名称" width="180" align="center" />
                        <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
                        <el-table-column prop="quantity" label="数量" width="120" align="center" />
                        <el-table-column prop="unitPrice" label="单价" width="120" align="center" />
                        <el-table-column prop="amount" label="金额" width="120" align="center" />
                    </el-table>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { createSalesReturn, getSalesReturnPage, getSalesReturnWithDetails, updateSalesReturn, deleteSalesReturn } from '@/api/sales/sales_return';
import { getSalesOutboundPage, getWarehouse, getSalesOutboundForReturn, getSalesOutboundById } from '@/api/sales/sales_outbound';
// 不再需要产品列表API，因为商品明细现在是只读的
// import { getProductList } from '@/api/warehouse/warehouse';

// 获取组件实例用于表单验证
const { proxy } = getCurrentInstance();

// 销售退货单列表数据
const salesReturnList = ref([]);

// 销售出库单列表数据（用于选择）
const salesOutbounds = ref([]);

// 仓库列表数据（用于选择）
const warehouses = ref([]);

// 不再需要产品列表数据，因为商品明细现在是只读的
// const productList = ref([]);

// 搜索参数
const searchParams = ref({
    returnNo: '',
    outboundNo: '',
    startDate: '',
    endDate: ''
});

// 分页参数
const pagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
});

// 对话框状态
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);

// 当前操作的销售退货单
const salesReturn = ref({});
const currentSalesReturn = ref(null);

// 仓库名称，用于在表单中显示
const warehouseName = ref('');

// 统一解包工具
function unwrap(res) {
  return (res && res.data !== undefined) ? res.data : res;
}

function unwrapPageRecords(payload) {
  const data = unwrap(payload);
  if (data && Array.isArray(data.records)) {
    return { records: data.records, total: Number(data.total) || data.records.length };
  }
  if (Array.isArray(data)) {
    return { records: data, total: data.length };
  }
  return { records: [], total: 0 };
}

// 表单验证规则
const formRules = ref({
    outboundId: [
        { required: true, message: '请选择出库单', trigger: 'blur' }
    ],
    warehouseId: [
        { required: true, message: '请选择仓库', trigger: 'blur' }
    ],
    returnDate: [
        { required: true, message: '请选择退货日期', trigger: 'change' }
    ]
});

// 获取销售退货单列表
function getSalesReturnList() {
    // 构建分页参数
    const pageParams = {
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
        returnNo: searchParams.value.returnNo,
        outboundNo: searchParams.value.outboundNo,
        startDate: searchParams.value.startDate,
        endDate: searchParams.value.endDate
    };

    getSalesReturnPage(pageParams).then(res => {
        const page = unwrapPageRecords(res);
        salesReturnList.value = page.records;
        pagination.value.total = page.total;
    }).catch(error => {
        ElMessage.error('获取销售退货单列表失败');
        console.error('获取销售退货单列表失败:', error);
    });
}

// 获取销售出库单列表（用于选择，排除已退货的出库单）
function fetchSalesOutbounds() {
    const pageParams = {
        pageNum: 1,
        pageSize: 1000 // 获取足够多的出库单
    };

    getSalesOutboundForReturn(pageParams).then(res => {
        const page = unwrapPageRecords(res);
        salesOutbounds.value = page.records;
    }).catch(error => {
        ElMessage.error('获取销售出库单列表失败');
        console.error('获取销售出库单列表失败:', error);
    });
}

// 获取仓库列表（用于选择）
function fetchWarehouses() {
  getWarehouse().then(res => {
    const data = unwrap(res);
    warehouses.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : []);
  }).catch(error => {
    ElMessage.error('获取仓库列表失败');
    console.error('获取仓库列表失败:', error);
  });
}

// 获取产品列表
function fetchProductList() {
    // getProductList().then(res => {
    //     const data = unwrap(res);
    //     productList.value = Array.isArray(data) ? data : [];
    // }).catch(error => {
    //     ElMessage.error('获取产品列表失败');
    //     console.error('获取产品列表失败:', error);
    // });
}

// 出库单选择变化时，自动填充仓库名称和商品明细
function handleOutboundChange(val) {
    if (val) {
        const outbound = salesOutbounds.value.find(o => o.id === val);
        if (outbound) {
            console.log('选中的出库单:', outbound);
            warehouseName.value = outbound.warehouseName || '';
            // 设置仓库ID，这样表单验证就能通过
            salesReturn.value.warehouseId = outbound.warehouseId;
            console.log('设置的仓库ID:', salesReturn.value.warehouseId);

            // 根据出库单ID获取商品明细
            getSalesOutboundById(val).then(res => {
                const data = unwrap(res);
                console.log('获取到的出库单详情:', data);
                if (data && data.items) {
                    salesReturn.value.items = data.items.map(item => ({
                        ...item,
                        productName: item.productName,
                        productCode: item.productCode,
                        amount: item.amount
                    }));
                    console.log('设置的商品明细:', salesReturn.value.items);
                } else {
                    salesReturn.value.items = [];
                }
            }).catch(error => {
                ElMessage.error('获取出库单详情失败');
                console.error('获取出库单详情失败:', error);
                salesReturn.value.items = [];
            });
        } else {
            warehouseName.value = '';
            salesReturn.value.warehouseId = null;
            salesReturn.value.items = [];
        }
    } else {
        warehouseName.value = '';
        salesReturn.value.warehouseId = null;
        salesReturn.value.items = [];
    }
}

// 重置搜索参数
function resetSearchParams() {
    searchParams.value = {
        returnNo: '',
        outboundNo: '',
        startDate: '',
        endDate: ''
    };
    getSalesReturnList();
}

// 分页处理
const handleSizeChange = (val) => {
    pagination.value.pageSize = val;
    getSalesReturnList();
}
const handleCurrentChange = (val) => {
    pagination.value.pageNum = val;
    getSalesReturnList();
}

// 明细操作方法
// function addItem() {
//     if (!salesReturn.value.items) salesReturn.value.items = [];
//     salesReturn.value.items.push({ productId: '', quantity: 1, unitPrice: 0, amount: 0 });
// }
// function removeItem(index) {
//     salesReturn.value.items.splice(index, 1);
// }
// function handleProductChange(row, val) {
//     // 自动带出产品名/编码等
//     const prod = productList.value.find(p => p.id === val);
//     if (prod) {
//         row.productName = prod.name;
//         row.productCode = prod.barcode || prod.code;
//         // 如果产品有默认价格，可以自动填入
//         if (prod.price && !row.unitPrice) {
//             row.unitPrice = prod.price;
//             calcAmount(row);
//         }
//     }
// }
// function calcAmount(row) {
//     row.amount = (Number(row.quantity) || 0) * (Number(row.unitPrice) || 0);
// }

// 显示创建对话框
function showAddDialog() {
    isEdit.value = false;
    salesReturn.value = {};
    dialogVisible.value = true;
    // 重置表单
    proxy.$refs.returnForm.resetFields();
    // 重置明细
    salesReturn.value.items = [];
    warehouseName.value = ''; // 重置仓库名称
    // 重置仓库ID
    salesReturn.value.warehouseId = null;
}

// 显示编辑对话框
function showEditDialog(row) {
    isEdit.value = true;
    // 获取完整的退货单信息（包含明细）
    getSalesReturnWithDetails(row.id).then(res => {
        const data = unwrap(res);
        salesReturn.value = data || {};
        // 确保明细数组存在
        if (!salesReturn.value.items) {
            salesReturn.value.items = [];
        }
        // 为每个明细项确保有正确的产品信息
        if (salesReturn.value.items && Array.isArray(salesReturn.value.items)) {
            salesReturn.value.items.forEach(item => {
                // 不再需要从产品列表中获取产品信息，因为商品明细现在是只读的
                // if (item.productId && !item.productName) {
                //     const product = productList.value.find(p => p.id === item.productId);
                //     if (product) {
                //         item.productName = product.name;
                //         item.productCode = product.barcode || product.code;
                //     }
                // }
                // 确保金额计算正确
                if (item.quantity && item.unitPrice) {
                    item.amount = (Number(item.quantity) || 0) * (Number(item.unitPrice) || 0);
                }
            });
        }
        // 如果出库单ID已存在，则自动填充
        if (salesReturn.value.outboundId) {
            handleOutboundChange(salesReturn.value.outboundId);
        }
        dialogVisible.value = true;
    }).catch(error => {
        ElMessage.error('获取销售退货单详情失败');
        console.error('获取退货单详情失败:', error);
        // 如果获取详情失败，使用基本信息
        salesReturn.value = { ...row, items: [] };
        dialogVisible.value = true;
    });
}

// 关闭对话框
function handleDialogClose() {
    dialogVisible.value = false;
    // 重置表单
    proxy.$refs.returnForm.resetFields();
    // 重置明细
    salesReturn.value.items = [];
    warehouseName.value = ''; // 重置仓库名称
    // 重置仓库ID
    if (salesReturn.value) {
        salesReturn.value.warehouseId = null;
    }
}

// 提交表单
function submitForm() {
    console.log('提交表单，当前数据:', salesReturn.value);

    proxy.$refs.returnForm.validate((valid) => {
        if (valid) {
            console.log('表单验证通过');

            // 明细校验
            if (!salesReturn.value.items || salesReturn.value.items.length === 0) {
                ElMessage.warning('请添加至少一条商品明细');
                return;
            }

            console.log('商品明细:', salesReturn.value.items);

            for (const item of salesReturn.value.items) {
                if (!item.productId || !item.quantity || !item.unitPrice) {
                    ElMessage.warning('请完善所有商品明细');
                    console.error('商品明细不完整:', item);
                    return;
                }
            }

            if (isEdit.value) {
                // 更新销售退货单
                console.log('更新销售退货单:', salesReturn.value);
                updateSalesReturn(salesReturn.value).then(res => {
                    ElMessage.success('销售退货单更新成功');
                    handleDialogClose();
                    getSalesReturnList();
                }).catch(error => {
                    ElMessage.error('销售退货单更新失败');
                    console.error('更新失败:', error);
                });
            } else {
                // 创建销售退货单
                salesReturn.value.status = 0;
                salesReturn.value.createUser = Number(localStorage.getItem("userId")) || 1;
                salesReturn.value.tenantId = Number(localStorage.getItem("tenantId")) || 1;

                console.log('创建销售退货单:', salesReturn.value);

                createSalesReturn(salesReturn.value).then(res => {
                    ElMessage.success('销售退货单创建成功');
                    handleDialogClose();
                    getSalesReturnList();
                }).catch(error => {
                    ElMessage.error('销售退货单创建失败');
                    console.error('创建失败:', error);
                    console.error('错误详情:', error.response?.data);
                });
            }
        } else {
            ElMessage.warning('请完善销售退货单信息并确保格式正确');
            console.error('表单验证失败');
            return false;
        }
    });
}

// 查看销售退货单详情
function viewSalesReturnDetails(id) {
    getSalesReturnWithDetails(id).then(res => {
        const data = unwrap(res);
        currentSalesReturn.value = data || null;
        detailDialogVisible.value = true;
    }).catch(error => {
        ElMessage.error('获取销售退货单详情失败');
        console.error('获取详情失败:', error);
    });
}

// 关闭详情对话框
function handleDetailDialogClose() {
    detailDialogVisible.value = false;
    currentSalesReturn.value = null;
}

// 删除销售退货单
function handleDeleteSalesReturn(id) {
    ElMessageBox.confirm(
        '确定要删除该销售退货单吗？此操作不可撤销。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        deleteSalesReturn(id).then(res => {
            ElMessage.success('销售退货单删除成功');
            getSalesReturnList();
        }).catch(error => {
            ElMessage.error('销售退货单删除失败');
            console.error('删除失败:', error);
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 获取出库单详情，包含商品明细
function getSalesOutboundWithDetails(outboundId) {
    return getSalesOutboundById(outboundId);
}

// 页面加载时获取销售退货单列表、销售出库单列表和仓库列表
onMounted(() => {
    getSalesReturnList();
    fetchSalesOutbounds();
    fetchWarehouses();
    // 不再需要获取产品列表，因为商品明细现在是只读的
    // fetchProductList();
});
</script>

<style scoped>
.sales-return-container {
    padding: 20px;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.sales-detail {
    padding: 10px;
}

.detail-header {
    margin-bottom: 20px;
}

.detail-header p {
    margin: 8px 0;
}

.label {
    font-weight: bold;
    display: inline-block;
    width: 100px;
}

.detail-items h3 {
    margin-bottom: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>


